﻿Friend Class BackupTabControl

    Public Sub Start()
        SetupEvents(True)
        For Each clsContract As Entities.Backup.IssuedContract In EntityHandlers.Backup.IssuedContracts.GetAll
            UpdateContract(clsContract)
        Next
        For Each clsContract As Entities.Backup.ReceivedContract In EntityHandlers.Backup.ReceivedContracts.GetAll
            UpdateContract(clsContract)
        Next
        For Each clsJob As Entities.Backup.Job In EntityHandlers.Backup.Jobs.GetAll
            UpdateJob(clsJob)
        Next
        PackageFileActivityControl1.Start()
        AnalyzeAndFindChangesActivityControl1.Start()
    End Sub
    Public Sub [Stop]()
        PackageFileActivityControl1.Stop()
        AnalyzeAndFindChangesActivityControl1.Stop()
        SetupEvents(False)
    End Sub
    Private Sub SetupEvents(ByVal startListening As Boolean)
        If startListening Then
            AddHandler EntityHandlers.Backup.IssuedContracts.UpdatedGUI, AddressOf EventHandler_BackupIssuedContractsUpdated
            AddHandler EntityHandlers.Backup.ReceivedContracts.UpdatedGUI, AddressOf EventHandler_BackupReceivedContractsUpdated
            AddHandler EntityHandlers.Backup.Jobs.UpdatedGUI, AddressOf EventHandler_BackupJobUpdated
            AddHandler EntityHandlers.Backup.Jobs.DeletedGUI, AddressOf EventHandler_BackupJobDeleted
            AddHandler Engine.Manager.JobInformationGUI, AddressOf EventHandler_JobInformation
        Else
            RemoveHandler EntityHandlers.Backup.IssuedContracts.UpdatedGUI, AddressOf EventHandler_BackupIssuedContractsUpdated
            RemoveHandler EntityHandlers.Backup.ReceivedContracts.UpdatedGUI, AddressOf EventHandler_BackupReceivedContractsUpdated
            RemoveHandler EntityHandlers.Backup.Jobs.UpdatedGUI, AddressOf EventHandler_BackupJobUpdated
            RemoveHandler EntityHandlers.Backup.Jobs.DeletedGUI, AddressOf EventHandler_BackupJobDeleted
            RemoveHandler Engine.Manager.JobInformationGUI, AddressOf EventHandler_JobInformation
        End If
    End Sub

    Private Sub EventHandler_BackupIssuedContractsUpdated(ByVal contract As Entities.Backup.IssuedContract)
        Try
            UpdateContract(contract)
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Sub EventHandler_BackupReceivedContractsUpdated(ByVal contract As Entities.Backup.ReceivedContract)
        Try
            UpdateContract(contract)
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Sub EventHandler_BackupJobUpdated(ByVal job As Entities.Backup.Job)
        Try
            UpdateJob(job)
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Sub EventHandler_BackupJobDeleted(ByVal job As Entities.Backup.Job)
        Try
            RemoveJob(job)
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub UpdateContract(ByVal contract As Entities.Backup.IssuedContract)
        Dim clsBuddy As Entities.Buddy = Framework.Buddies.Manager.GetById(contract.IssuedToBuddyId)
        Dim strKey As String = contract.UniqueId
        Dim clsItem As ListViewItem
        If lvwIssued.Items.ContainsKey(strKey) Then
            clsItem = lvwIssued.Items(strKey)
        Else
            clsItem = lvwIssued.Items.Add(strKey, String.Empty, CStr(Nothing))
            clsItem.SubItems.Add(String.Empty)
            clsItem.SubItems.Add(String.Empty)
            clsItem.SubItems.Add(String.Empty)
        End If
        If clsBuddy Is Nothing Then
            clsItem.Text = "Unknown"
        Else
            clsItem.Text = clsBuddy.NameLocal
        End If
        clsItem.SubItems(1).Text = Framework.Misc.ToReadableFileSize(contract.StorageSize)
        clsItem.SubItems(2).Text = CStr(IIf(contract.Revoked, "Yes", "No"))
        clsItem.SubItems(3).Text = contract.StoragePath
        clsItem.Tag = contract
    End Sub
    Private Sub UpdateContract(ByVal contract As Entities.Backup.ReceivedContract)
        Dim clsBuddy As Entities.Buddy = Framework.Buddies.Manager.GetById(contract.IssuedByBuddyId)
        Dim strKey As String = contract.Id.ToString
        Dim clsItem As ListViewItem
        If lvwReceived.Items.ContainsKey(strKey) Then
            clsItem = lvwReceived.Items(strKey)
        Else
            clsItem = lvwReceived.Items.Add(strKey, String.Empty, CStr(Nothing))
            clsItem.SubItems.Add(String.Empty)
            clsItem.SubItems.Add(String.Empty)
            clsItem.SubItems.Add(String.Empty)
        End If
        If clsBuddy Is Nothing Then
            clsItem.Text = "Unknown"
        Else
            clsItem.Text = clsBuddy.NameLocal
        End If
        clsItem.SubItems(1).Text = Framework.Misc.ToReadableFileSize(contract.StorageSize)
        clsItem.SubItems(2).Text = CStr(IIf(contract.Revoked, "Yes", "No"))
        clsItem.SubItems(3).Text = contract.Comment
        clsItem.Tag = contract
    End Sub
    Private Sub RemoveJob(ByVal job As Entities.Backup.Job)
        Dim strKey As String = job.Id.ToString
        If lvwJobs.Items.ContainsKey(strKey) Then
            lvwJobs.Items(strKey).Remove()
        End If
    End Sub
    Private Sub UpdateJob(ByVal job As Entities.Backup.Job)
        Dim strKey As String = job.Id.ToString
        Dim clsItem As ListViewItem
        If lvwJobs.Items.ContainsKey(strKey) Then
            clsItem = lvwJobs.Items(strKey)
        Else
            clsItem = lvwJobs.Items.Add(strKey, String.Empty, CStr(Nothing))
            clsItem.SubItems.Add(String.Empty)
            clsItem.SubItems.Add(String.Empty)
            clsItem.SubItems.Add(String.Empty)
            clsItem.SubItems.Add(String.Empty)
            clsItem.SubItems.Add(String.Empty)
            clsItem.UseItemStyleForSubItems = True
        End If
        clsItem.Text = job.Name
        If job.Schedule IsNot Nothing AndAlso job.Schedule.HasKnownNextRunTime Then
            clsItem.SubItems(3).Text = job.NextRunUtc.ToLocalTime.ToString("g")
        ElseIf job.Schedule IsNot Nothing Then
            clsItem.SubItems(3).Text = "Undeterminable"
        Else
            clsItem.SubItems(3).Text = "Missing schedule"
        End If
        If job.LastRunUtc <> DateTime.MinValue Then
            clsItem.SubItems(4).Text = job.LastRunUtc.ToLocalTime.ToString("g")
        Else
            clsItem.SubItems(4).Text = "Never run"
        End If
        clsItem.SubItems(5).Text = job.Comment
        clsItem.Tag = job
        If job.Enabled Then
            clsItem.SubItems(1).Text = "Yes"
            clsItem.ForeColor = Drawing.SystemColors.WindowText
        Else
            clsItem.SubItems(1).Text = "No"
            clsItem.ForeColor = Drawing.SystemColors.InactiveCaptionText
        End If
        clsItem.SubItems(2).Text = job.Status.ToString
    End Sub


    Private Sub IssueNewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IssueNewToolStripMenuItem.Click
        Dim clsView As New FIssueContract
        clsView.ShowDialog(Me)
    End Sub

    Private Sub PropertiesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PropertiesToolStripMenuItem.Click
        EventHandler_EditSelectedContract()
    End Sub

    Private Sub EventHandler_EditSelectedContract()
        Try
            If lvwIssued.SelectedItems.Count <> 1 Then Beep() : Return
            Dim clsContract As Entities.Backup.IssuedContract = CType(lvwIssued.SelectedItems(0).Tag, Entities.Backup.IssuedContract)
            Dim clsView As New FEditContract
            clsView.ShowDialog(Me, clsContract)
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub EventHandler_EditSelectedJob()
        Try
            If lvwJobs.SelectedItems.Count <> 1 Then Beep() : Return
            Dim clsJob As Entities.Backup.Job = CType(lvwJobs.SelectedItems(0).Tag, Entities.Backup.Job)
            Dim clsView As New FEditJob
            clsView.Show(Me, clsJob)
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub NewJobToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewJobToolStripMenuItem.Click
        EventHandler_NewJob()
    End Sub
    Private Sub EventHandler_NewJob()
        Try
            Dim clsJob As Entities.Backup.Job = EntityHandlers.Backup.Jobs.CreateNew
            Dim clsView As New FEditJob
            clsView.Show(Me, clsJob)
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub lvwJobs_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvwJobs.DoubleClick
        EventHandler_EditSelectedJob()
    End Sub

    Private Sub PropertiesToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PropertiesToolStripMenuItem1.Click
        EventHandler_EditSelectedJob()
    End Sub

    Private Sub EnableJob_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EnableJob.Click
        Try
            For Each clsJob As Entities.Backup.Job In GetSelectedJobs()
                clsJob.Enabled = Not clsJob.Enabled
                EntityHandlers.Backup.Jobs.Save(clsJob)
            Next
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub cmJobs_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles cmJobs.Opening
        Try
            DeleteJobs.Enabled = lvwJobs.SelectedItems.Count > 0
            QueueJobToStartAsSoonAsPossible.Enabled = lvwJobs.SelectedItems.Count > 0

            Dim aJobs As Generic.List(Of Entities.Backup.Job) = GetSelectedJobs()
            If aJobs.Count = 0 Then
                EnableJob.Enabled = False
                CopyJob.Enabled = False
                PropertiesToolStripMenuItem1.Enabled = False
                QueueJobToStartAsSoonAsPossible.Enabled = False
                AbortRunningJob.Enabled = False
            ElseIf aJobs.Count = 1 Then
                Dim clsJob As Entities.Backup.Job = CType(lvwJobs.SelectedItems(0).Tag, Entities.Backup.Job)
                EnableJob.Checked = clsJob.Enabled
                EnableJob.Enabled = True
                CopyJob.Enabled = True
                PropertiesToolStripMenuItem1.Enabled = True
                QueueJobToStartAsSoonAsPossible.Enabled = clsJob.Status = Entities.Backup.JobStatus.Idle
                AbortRunningJob.Enabled = clsJob.Status = Entities.Backup.JobStatus.Running
            Else
                QueueJobToStartAsSoonAsPossible.Enabled = True
                AbortRunningJob.Enabled = True
                EnableJob.Enabled = True
                Dim blnAllJobEnabled As Boolean = True
                Dim blnAllJobDisabled As Boolean = True
                For Each clsJob As Entities.Backup.Job In aJobs
                    Select Case clsJob.Status
                        Case Entities.Backup.JobStatus.Running
                            QueueJobToStartAsSoonAsPossible.Enabled = False
                        Case Entities.Backup.JobStatus.Idle
                            AbortRunningJob.Enabled = False
                        Case Else
                            Throw New NotImplementedException
                    End Select
                    If clsJob.Enabled Then
                        blnAllJobDisabled = False
                    Else
                        blnAllJobEnabled = False
                    End If
                Next
                If blnAllJobDisabled Then
                    EnableJob.Checked = False
                    EnableJob.Enabled = True
                ElseIf blnAllJobEnabled Then
                    EnableJob.Checked = True
                    EnableJob.Enabled = True
                Else
                    EnableJob.Checked = False
                    EnableJob.Enabled = False
                End If
                PropertiesToolStripMenuItem1.Enabled = False
            End If
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub CopyJob_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyJob.Click
        Try
            If lvwJobs.SelectedItems.Count = 1 Then
                Dim clsJob As Entities.Backup.Job = CType(lvwJobs.SelectedItems(0).Tag, Entities.Backup.Job)
                clsJob = EntityHandlers.Backup.Jobs.Copy(clsJob)
                Dim clsView As New FEditJob
                clsView.Show(Me, clsJob)
            End If
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub DeleteJobs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteJobs.Click
        Try
            Select Case MessageBox.Show(Me, "Delete jobs?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                Case DialogResult.Yes
                    EntityHandlers.Backup.Jobs.Delete(GetSelectedJobs)
            End Select
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Function GetSelectedJobs() As Generic.List(Of Entities.Backup.Job)
        Dim aJobs As New Generic.List(Of Entities.Backup.Job)
        For Each clsItem As ListViewItem In lvwJobs.SelectedItems
            aJobs.Add(CType(clsItem.Tag, Entities.Backup.Job))
        Next
        Return aJobs
    End Function

    Private Sub QueueJobToStartAsSoonAsPossible_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QueueJobToStartAsSoonAsPossible.Click
        Try
            For Each clsJob As Entities.Backup.Job In GetSelectedJobs()
                If clsJob.Status = Entities.Backup.JobStatus.Idle Then
                    clsJob.NextRunUtc = Now.ToUniversalTime
                    EntityHandlers.Backup.Jobs.Save(clsJob)
                End If
            Next
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Sub EventHandler_JobInformation(ByVal job As Entities.Backup.Job, ByVal information As String)
        Try
            Dim clsItem As New ListViewItem
            clsItem.Text = Now.ToString("g")
            clsItem.SubItems.Add(job.Name)
            clsItem.SubItems.Add(information)
            lvwLog.BeginUpdate()
            lvwLog.Items.Add(clsItem)
            While lvwLog.Items.Count > 100
                lvwLog.Items.RemoveAt(0)
            End While
            lvwLog.EnsureVisible(clsItem.Index)
            lvwLog.EndUpdate()
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub AbortRunningJob_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AbortRunningJob.Click
        Try
            Select Case MessageBox.Show("Abort running backup(s)??", "Abort backup", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
                Case DialogResult.OK
                    For Each clsJob As Entities.Backup.Job In GetSelectedJobs()
                        Engine.Manager.AbortJob(clsJob)
                    Next
            End Select
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub
End Class
